import { User } from './../entitys/User';
import { stringify } from 'querystring';
import AuthService from "../services/AuthService"
import { Context } from 'koa';
import { pathToRegexp } from "path-to-regexp"
import Response from '../common/response';
const authService = new AuthService()
let keys: any[] = []
const whiteList = [pathToRegexp("/login"), pathToRegexp("/captcha"), pathToRegexp('/file'), pathToRegexp('/loginLog/:path(.*)', keys, { end: false })]
const urlPrefix = "/api"
const whiteIp = [
    '112.224.141.185',
    //'192.168.0.100'
]
export async function auth(ctx: Context, next: (err?: any) => Promise<any>) {
    let { url } = ctx.request
    const req: any = ctx.req
    let index = url.lastIndexOf("?")
    if (index > -1) {
        url = url.substring(0, index)
    }
    url = url.replace(urlPrefix, "")
    if (whiteList.some(regex => regex.test(url))) {
        return next()
    }

    let token = ctx.header.token
    if (!token) {
        return ctx.response.status = 401
    }
    var ip = req.headers['x-forwarded-for'] ||
        req.ip ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress || '';
    if (ip.split(',').length > 0) {
        ip = ip.split(',')[0]
    }
    ip = ip.substr(ip.lastIndexOf(':') + 1, ip.length);
    if (!whiteIp.includes(ip.trim()) && ctx.method !== 'GET') {
        ctx.response.status = 400
        ctx.response.body = Response.BAD_REQUEST("当前演示环境没有权限")
        return
    }
    try {
        ctx.userInfo = await authService.checkToken(token)
    } catch (err) {
        if (err === false) {
            return ctx.response.status = 401
        } else {
            return ctx.response.status = 500
        }
    }
    return next()
}